<template>
  <div>
    <div class="header-btn">
      <div>上传文件</div>
      <div>
        <el-button type="primary" @click="createFile" v-has-permi="['wecom:material:edit']" :loading="sureLoading">确认</el-button>
        <el-button type="info" plain @click="back">返回</el-button>
      </div>
    </div>
    <div class="wrap g-card" style="margin-bottom: 20px">
      <el-upload
        class="upload-demo"
        :show-file-list="false"
        drag
        action
        :before-upload="uploadFile"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <div v-for="(item, index) in fileList" :key="index" style="width: 200px">
            <div
              @mouseenter="iconShow = false"
              @mouseleave="iconShow = true"
              style="width: 200px; margin-bottom: 5px"
            >
              {{ item.name }}
              <i
                v-show="iconShow"
                class="el-icon-circle-check"
                style="color: greenyellow; float: right"
              ></i>
              <i
                @click="deleteText"
                v-show="!iconShow"
                class="el-icon-close"
                style="float: right"
              ></i>
            </div>
          </div>
          支持Word，excel，ppt，pdf格式的文件
        </div>
      </el-upload>

      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="个人分组" prop="newPersonGroupId">
          <el-select
            v-model="form.newPersonGroupId"
            placeholder="请选择分组"
            style="width: 400px"
          >
            <el-option
              v-for="item in groupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面" required>
          <div class="upload">
            <el-upload
              action
              :before-upload="beforeUploadImg"
              :show-file-list="false"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div class="el-upload__tip" slot="tip">
                建议上传800*800像素的图片
              </div>
            </el-upload>
            <div v-for="(item, index) in imgs" class="img" :key="index">
              <i class="el-icon-circle-close" @click="handleRemove(index)"></i>
              <img v-if="item" :src="item" width="100%"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="摘要" prop="text">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请添加备注"
            v-model="form.text"
            style="width: 400px"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="其他设置" v-if="this.$route.query.is_person == 1">
          <el-checkbox v-model="form.isSync">同步到企业文件库</el-checkbox>
        </el-form-item>
        <el-form-item label="打标签">
            <tag-group v-model="form.weGroupTagVOS" />
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加标签 -->
<!--    <el-dialog :title="`客户标签`" :visible.sync="tagVisible" width="20%">-->
<!--      <el-form :model="tagForm" :rules="tagRules" ref="tagForm">-->
<!--        <el-form-item label="标签" prop="tagName" label-width="50px">-->
<!--          <el-input-->
<!--            v-model.trim="tagForm.tagName"-->
<!--            clearable-->
<!--            maxlength="32"-->
<!--            placeholder="输入多个标签以;分隔"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer">-->
<!--        <el-button type="primary" @click="confirm">确 定</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
    <!-- <MakeLabel :visible.sync="tagVisible" :label.sync="tagForm.tagName" @confirm="confirm"></MakeLabel> -->
  </div>
</template>

<script>
import {
  createFile,
  createFileCorp,
  getFileDetails,
  queryGroupsList,
  uploadFile,
  uploadImgFile
} from '../../../../api/communityOperating/fileManage.js'

import MakeLabel from "@/components/MakeLabel/index.vue";

export default {
  name: 'UploadFile',

  data() {
    // var labelValdator = (rule, value, callback) => {
    //   // console.log(this.tagForm.tagName);
    //   if (!this.dynamicTags.length) {
    //     return callback(new Error("请添加标签"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      iconShow: true,
      checked: false,
      form: {
        newPersonGroupId: '',
        text: '',
        isSync: false,
        newCompanyGroupId: '',
        weGroupTagVOS: []
      },
      tagForm: {
        tagName: ''
      },
      groupOptions: [],
      groupOptions1: [],
      imgs: [], //图片组
      fileList: [],
      tagVisible: false,
      dialogImageUrl: '',
      dialogVisible: false,
      dynamicTags: [], //标签
      tagRules: {
        tagName: [{ required: true, message: '请输入标签', trigger: 'blur' }]
      },
      rules: {
        newPersonGroupId: [
          { required: true, message: '请选择分组名称', trigger: 'blur' }
        ],
        text: [{ max: 640, message: '您录入字数超过640字', trigger: 'blur' }]
        // label: [{ validator: labelValdator, trigger: "blur" }],
        // imgs: [
        //     { validator: validateImgs, trigger: 'blur' }
        //   ],
        // label: [
        //   { validator: validateLabel, trigger: 'blur' }
        // ],
      },
      sureLoading : false,
    }
  },
  methods: {
    beforeFillUpload(file) {
      console.log(file.type, 'file.type')
      return
    },
    // 打标签
    confirm(value) {
      // this.$refs.tagForm.validate((isok) => {
      //   if (isok) {
          const tag = value.split(/[；;]/g)
          this.dynamicTags = [...this.dynamicTags, ...tag]
          this.dynamicTags = Array.from(new Set(this.dynamicTags))
          this.dynamicTags = this.dynamicTags.filter(item => item !== '' && !item.match(/^[ ]*$/))
          // this.tagVisible = false
          // this.$refs.tagForm.resetFields()
          this.tagForm.tagName = ''
        // }
      // })
    },
    // 删除标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    // 上传文件
    async uploadFile(file) {
      console.log(file)
      const type = [
        'text/plain',
        'application/vnd.ms-powerpoint',
        'application/vnd.ms-excel',
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/msword'
      ]
      const isFile = type.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isFile) {
        this.$message.error('仅支持word,excel,ppt,pdf格式的文件!')
        return false
      } else if (!isLt2M) {
        this.$message.error('您上传的文件超过10M!')
      } else {
        const formData = new FormData()
        formData.append('file', file)
        const { data } = await uploadFile(formData)
        this.form.fileName = data.fileName
        this.form.fileUrl = data.url
        this.fileList = [
          {
            name: data.fileName,
            url: data.url
          }
        ]
      }
    },
    // 上传图片之前
    async beforeUploadImg(img) {
      console.log(img)
      const type = ['image/png', 'image/jpg', 'image/gif', 'image/jpeg']
      const isJPG = type.includes(img.type)
      const isLt10M = img.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片支持jpg、png、gif格式!')
      } else if (!isLt10M) {
        this.$message.error('您上传的文件超过10MB!')
      } else {
        console.log(img, '====img')
        const formData = new FormData()
        formData.append('file', img)
        const { data } = await uploadImgFile(formData)
        this.imgs = [window.globalConfig.IMAGE_API + data.url]
        console.log(this.imgs[0])
        this.form.photoName = data.photoName
        this.form.photoUrl = data.url
      }
    },
    handleRemove(index) {
      this.imgs.splice(index, 1)
    },
    deleteText() {
      this.fileList = []
      this.iconShow = true
    },
    // 新增文件
    createFile() {
      // console.log('this.form.label', this.form.weGroupTagVOS);
      // console.log(this.form.isSync)
      if (!this.fileList.length) {
        this.$message.error('您的文件未上传')
        return
      }
      if (!this.imgs.length) {
        this.$message.error('您的封面未上传')
        return
      }
        const data = {
          id: this.$route.query.id || null,
          // groupLevel: '1',
          groupLevel: this.$route.query.levelType === '0' ? '0' : '1',
          newPersonGroupId: this.form.newPersonGroupId,
          text: this.form.text,
          fileName: this.form.fileName,
          fileUrl: this.fileList[0].url,
          photoName: this.form.photoName,
          photoUrl: this.form.photoUrl,
          isSync: this.form.isSync ? '1' : '0',
          newCompanyGroupId: this.form.newCompanyGroupId || null,
          // label: this.dynamicTags.join(';')
          // label: this.form.label
          weGroupTagVOS: this.form.weGroupTagVOS || []
        }
        if (this.$route.query.id) {
          data.id = this.$route.query.id
        }
        this.$refs.form.validate(async(isok) => {
          if (isok) {
            let res = ''
            this.sureLoading = true;
            if (+this.$route.query.levelType === 0) {
              res = await createFileCorp(data)
            } else {
              res = await createFile(data)
            }
            if (res.code === 200) {
              this.$message.success(
                this.$route.query.id ? '编辑文件成功' : '新增文件成功'
              )
              this.back()
            } else {
              this.$message.error(
                this.$route.query.id ? '编辑文件失败' : '新增文件失败'
              )
            }
            this.sureLoading = false;
          }
        })
      },
    //返回
    back() {
      this.$router.push({ name: 'FileManagement', query: { is_person: this.$route.query.is_person } })
    },
    //初始化方法
    async init() {
      await queryGroupsList({ levelType: 1, mediaType: 3 }).then(res => {
        this.groupOptions = res.data
      }).catch(() => {
      })
      // console.log(this.$route.query);
      if (this.$route.query.fileInfo) {
        this.$route.query.fileInfo.newPersonGroupId =
          this.$route.query.fileInfo.groupId
      }
      if (this.$route.query.id) {
        getFileDetails({ id: this.$route.query.id }).then(res => {
          if (res.code === 200) {

      // let res.data = JSON.parse(JSON.stringify(row))
            if(res.data.weGroupTagVOS){
              res.data.weGroupTagVOS1 = JSON.parse(JSON.stringify(res.data.weGroupTagVOS))
              res.data.weGroupTagVOS = []
              res.data.weGroupTagVOS1.forEach(tagGroup=>{
                tagGroup.tagName.split(',').forEach(tagName=>{
                  res.data.weGroupTagVOS.push({groupName:tagGroup.groupName,tagName})
                })
              })
            }

            this.form = res.data
            this.fileList.push({
              name: res.data.fileName,
              url: res.data.fileUrl
            })
            // this.form.newPersonGroupId = String(res.data.groupId)
            this.$set(this.form, 'newPersonGroupId', res.data.groupId)
            this.imgs.push(
              window.globalConfig.IMAGE_API + res.data.photoUrl
            )
            // this.dynamicTags = res.data.label.split(';')
            // this.tagForm.tagName = res.data.label || ''
            this.form['isSync'] = res.data.isSync == '1' ? true : false

            // console.log('form.isSync', this.form.isSync);
          }
        }).catch(() => {
        })
      }
    }
  },
  components: {
    MakeLabel,
  },
  mounted() {
    // console.log('this.$route.query.levelType',this.$route.query.levelType);
    this.init()
  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
  padding-top: 16px;
  padding-left: 20px;
}

.img {
  position: relative;
  width: 148px;
  height: 148px;
  margin-right: 10px;

  img {
    height: 100%;
  }

  i {
    position: absolute;
    top: -5px;
    right: -5px;
    z-index: 10;
  }
}

.upload {
  display: flex;
}
</style>
